import React, { useEffect, useRef, useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import {
  View,
  Swiper,
  SwiperItem,
  Text,
  Image,
  Button,
  Video,
} from "@tarojs/components";
import CustomFloatLayout from "@/components/CustomFloatLayout";
import { getToken } from "@/src/service";
import waitOpenToast from "@/common/utils/waitOpenToast";
import customNavigate from "@/common/hooks/useNavigate";
import iconRight from "@/images/icon_right.jpg";
import iconKefu from "@/images/order_icon_service.png";
import iconShoucang from "@/images/order_icon_collect.png";
import iconShoucangSelected from "@/images/collected_icon.png";

import * as api from "./api";
import * as collectApi from "../collectList/api";
import { GoodsDetailData, SkuItData } from "./data";
import "./index.scss";

const Index: React.FC<{}> = () => {
  const router = useRouter();
  const [goodsData, setGoodsData] = useState<
    Partial<GoodsDetailData & { deposit: number; id: number }>
  >({});
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(0);
  const layoutRef = useRef();
  const [cateList, setCatList] = useState<SkuItData[]>([]);
  const [count, setCount] = useState(1);
  const [collectList, setCollectList] = useState(
    Taro.getStorageSync("collectIds")
  );
  const [currentSkuIt, setCurrentSkuIt] = useState<
    Partial<SkuItData & { original_price: number }>
  >({
    show_image: "",
  });

  const getGoodsData = async () => {
    try {
      setLoading(true);
      const { result, status } = await api.production_goods_get({
        goods_id: router.params.goods_id,
      });
      console.log(result.goods_info);
      if (status === "ok") {
        setGoodsData(result.goods_info);
        setCatList(result.goods_info.specification_list);
        setCurrentSkuIt(result.goods_info.specification_list[0]);
        if (result.goods_info.specification_list[0].stock === 0) {
          setCount(0);
        }
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      setLoading(false);
    }
  };

  const getGoodsDataByPoster = async () => {
    try {
      setLoading(true);
      const { result, status } = await api.production_poster_get({
        poster_id: router.params.poster_id,
      });
      console.log(result, status);
      if (status === "ok") {
        setGoodsData(result.goods_info);
        setCatList(result.goods_info.specification_list);
        setCurrentSkuIt(result.goods_info.specification_list[0]);
        if (result.goods_info.specification_list[0].stock === 0) {
          setCount(0);
        }
      } else {
        setTimeout(() => {
          Taro.switchTab({
            url: "/pages/index/index",
          });
        }, 2000);
      }
    } catch (err) {
      // Taro.switchTab({
      //   url: "/pages/index/index",
      // });
      console.log("err--------->>>", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (router.params.poster_id) {
      if (getToken().access_token) {
        getGoodsDataByPoster();
      } else {
        Taro.navigateTo({
          url: "/pages/loginGuide/index",
        });
      }
    } else {
      getGoodsData();
    }
  }, [router]);

  const onSwiperChange = (e: any) => {
    setCurrent(e.detail.current);
  };

  const despatch_type_map: any = {
    logistics: "物流",
    phone_top_up: "手机充值",
    eduction_contract: "教育合同",
  };

  const onChangeCount = (type: "add" | "minus") => {
    let newCount = count;
    if (type === "add") {
      if (count < 1 && count < currentSkuIt.stock) {
        newCount++;
      }
    } else {
      if (count > 1) {
        newCount--;
      }
    }
    setCount(newCount);
  };

  const onSelectCate = (id: number) => {
    const newCurrentSkuIt = cateList.find((it) => it.id === id);
    if ((newCurrentSkuIt as SkuItData).stock === 0) {
      setCount(0);
    } else {
      setCount(1);
    }
    setCurrentSkuIt(newCurrentSkuIt);
  };

  const goConfirmOrder = () => {
    (layoutRef.current as any).hide();
    const routerParams = {
      count: count,
      cateInfo: currentSkuIt,
      goodsInfo: goodsData,
      poster_id: router.params.poster_id,
    };
    customNavigate(
      `/pages/orderConfirm/index?params=${JSON.stringify(routerParams)}`
    );
  };

  const collect = async () => {
    const { result, status } = await collectApi.customer_collection_collection({
      goods_id: goodsData.id || router.params.goods_id,
    });
    if (status === "ok") {
      let collectIds = Taro.getStorageSync("collectIds");
      const index = collectIds.indexOf(goodsData.id || router.params.goods_id);
      if (index > -1) {
        collectIds.splice(index, 1);
        setCollectList(collectIds);
        Taro.showToast({
          icon:'none',
          title:'取消成功'
        })
        Taro.setStorageSync("collectIds", collectIds);
      } else {
        collectIds.push(goodsData.id || router.params.goods_id);
        setCollectList(collectIds);
        Taro.showToast({
          icon:'none',
          title:'收藏成功'
        })
        Taro.setStorageSync("collectIds", collectIds);
      }
    }
  };

  return goodsData.title ? (
    <View className="goods-detail-page">
      <View className="banner-wrapper">
        <Swiper
          className="banner"
          indicatorColor="#999"
          indicatorActiveColor="#333"
          circular
          indicatorDots={false}
          onChange={onSwiperChange}
          current={current}
        >
          {goodsData.video_display && (
            <SwiperItem>
              <Video
                src={goodsData.video_display}
                autoplay={false}
                controls
                enablePlayGesture
              />
            </SwiperItem>
          )}
          {goodsData.slideshow &&
            goodsData.slideshow.map((item) => (
              <SwiperItem key={item}>
                <Image src={item} />
              </SwiperItem>
            ))}
        </Swiper>
        {goodsData.video_display && (
          <View className="footer-page">
            <View
              className={current === 0 ? "tag tag__selected" : "tag"}
              onClick={() => {
                setCurrent(0);
              }}
            >
              视频
            </View>
            <View
              className={current !== 0 ? "tag tag__selected" : "tag"}
              onClick={() => {
                setCurrent(1);
              }}
            >
              图片
            </View>
          </View>
        )}

        {goodsData.video_display ? (
          <View>
            {current !== 0 && (
              <View className="indicator">
                {goodsData.video_display ? current : current + 1}/
                {goodsData.slideshow?.length}
              </View>
            )}
          </View>
        ) : (
          <View className="indicator">
            {current + 1}/{goodsData.slideshow?.length}
          </View>
        )}
      </View>

      <View className="info">
        {router.params.poster_id ? (
          <View className="price">
            <Text className="symbol">￥</Text>
            <Text className="money">
              {((currentSkuIt.sale_price as number) / 100).toFixed(2)}
            </Text>
            <Text className="old_price">
              ￥{((currentSkuIt.original_price as number) / 100).toFixed(2)}
            </Text>
          </View>
        ) : (
          <View className="price">
            <Text className="symbol">￥</Text>
            <Text className="money">
              {((goodsData.min_price as number) / 100).toFixed(2)}
            </Text>
          </View>
        )}

        <View className="goods-name">{goodsData.title}</View>
        <View className="desc">{goodsData.description}</View>
      </View>

      <View className="opt-wrapper">
        <View className="opt-it">
          <View className="label">发货</View>
          <View className="value">
            {
              despatch_type_map[
                goodsData.despatch_type as keyof Pick<
                  GoodsDetailData,
                  "despatch_type"
                >
              ]
            }
          </View>
        </View>
      </View>

      <View className="opt-wrapper">
        <View className="opt-it">
          <View className="label">学校</View>
          <View className="value">{goodsData.school_name}</View>
        </View>
        <View className="opt-it">
          <View className="label">专业</View>
          <View className="value">{goodsData.major_name}</View>
        </View>
        <View className="opt-it">
          <View className="label">学年</View>
          <View className="value">{goodsData.duration}</View>
        </View>
      </View>

      <View className="opt-wrapper">
        <View
          className="opt-it"
          onClick={layoutRef.current && layoutRef.current.show}
        >
          <View className="label">类型</View>
          <View className="value">
            {currentSkuIt.specification_value_list &&
              currentSkuIt.specification_value_list.length && (
                <Text>
                  {currentSkuIt.specification_value_list.map((it, idx) => {
                    return `${it.attribute}${
                      idx < currentSkuIt.specification_value_list.length - 1
                        ? "/"
                        : ""
                    }`;
                  })}
                </Text>
              )}
          </View>
          <Image className="icon" src={iconRight} />
        </View>
        <View className="opt-it">
          <View className="label">报考</View>
          <View className="value">{goodsData.brand_name}</View>
        </View>
        <View className="opt-it">
          <View className="label">层次</View>
          <View className="value">{goodsData.production_name}</View>
        </View>
      </View>

      <View className="separate">
        <Text>图文详情</Text>
      </View>

      {goodsData.detail &&
        goodsData.detail.map((item) => (
          <Image
            mode="widthFix"
            lazyLoad
            showMenuByLongpress
            className="detail-image"
            src={item}
            key={item}
          />
        ))}

      <View className="blank"></View>
      <View className="footer-content">
        <View className="l">
          <Button className="item" openType="share">
            <Image className="icon" src={iconKefu} />
            <Text>客服</Text>
          </Button>
          <View className="item" onClick={collect}>
            <Image
              className="icon"
              src={
                collectList.includes(goodsData.id || router.params.goods_id)
                  ? iconShoucangSelected
                  : iconShoucang
              }
            />
            <Text>收藏</Text>
          </View>
        </View>
        <View className="r">
          <View
            className="button"
            onClick={() => {
              if (getToken().access_token) {
                layoutRef.current?.show();
              } else {
                Taro.navigateTo({
                  url: "/pages/loginGuide/index",
                });
              }
            }}
          >
            立即购买
          </View>
        </View>
      </View>

      <CustomFloatLayout ref={layoutRef}>
        <View className="sku-content">
          <View className="top">
            <View className="sub-title">报考信息</View>
            <View className="sku-info">
              <Image className="logo" src={currentSkuIt.show_image || ""} />
              <View className="sku-info-it">
                <View className="price">
                  <Text className="symbol">￥</Text>
                  {currentSkuIt.sale_price && (
                    <Text className="money">
                      {(currentSkuIt.sale_price / 100).toFixed(2)}
                    </Text>
                  )}
                  {router.params.poster_id && (
                    <Text className="old_price">
                      ￥{(currentSkuIt.original_price / 100).toFixed(2)}
                    </Text>
                  )}
                </View>
                <View className="stock">库存{currentSkuIt.stock}件</View>
                <View className="cate-desc">
                  已选择："
                  {currentSkuIt.specification_value_list &&
                    currentSkuIt.specification_value_list.length && (
                      <Text>
                        {currentSkuIt.specification_value_list.map(
                          (it, idx) => {
                            return `${it.attribute}${
                              idx <
                              currentSkuIt.specification_value_list.length - 1
                                ? "/"
                                : ""
                            }`;
                          }
                        )}
                      </Text>
                    )}
                  "
                </View>
              </View>
            </View>
          </View>

          <View className="tag-wrapper">
            <View className="sub-title">选择类型</View>
            {cateList.map((item) => (
              <View
                className={
                  currentSkuIt.id === item.id ? "tag tag__select" : "tag"
                }
                key={item.id}
                onClick={() => onSelectCate(item.id)}
              >
                <Image src={item.show_image} />
                <Text>
                  {item.specification_value_list.map((it, idx) => {
                    return `${it.attribute}${
                      idx < item.specification_value_list.length - 1 ? "/" : ""
                    }`;
                  })}
                </Text>
              </View>
            ))}
          </View>

          <View className="count">
            <View className="sub-title">购买数量</View>
            <View className="set-count">
              <View className="minus" onClick={() => onChangeCount("minus")}>
                -
              </View>
              <View className="buy-count">{count}</View>
              <View className="add" onClick={() => onChangeCount("add")}>
                +
              </View>
            </View>
          </View>
          <View className="footer-btn">
            {count > 0 ? (
              <View className="submit-btn" onClick={goConfirmOrder}>
                确定
              </View>
            ) : (
              <View className="submit-btn submit-btn__disabled">确定</View>
            )}
          </View>
        </View>
      </CustomFloatLayout>
    </View>
  ) : null;
};

export default Index;
